#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
#define PATH "/dev/my_led"
#define OPT_STRING    ":r:g:b:"   // 选项字符串
void print_usage()
{
    printf("Usage: ./test -r <on/off> -g <on/off> -b <on/off>\n"
           "-r: Control red led\n"
           "-g: Control green led\n"
           "-b: Control blue led\n" 
           "on: Light on(default)\n"
           "off: Light off\n");
}

extern char* optarg;  // 指向参数值
extern int optind;    // 记录getopt函数处理argv[]数组的位置，一般不需要设置
extern int opterr;    // 保存出错信息，非0 getopt会向stderr打印出错信息，如为0时则不打印
/* 遇到无法识别的选项，getopt返回？号，并将？存储到optopt中，如果将选项字符串第一个字符设置
   为：号，那么getopt函数在用户未提供值的情况下返回：号而不是？号 */
extern int optopt; 
int parse_option(int argc, char* argv[], int* rgb)
{
    int opt;
    while (-1 != (opt = getopt(argc, argv, OPT_STRING))) {
        switch (opt) {
        case 'r':
            if(0 == strcmp(optarg, "on")) rgb[0] = 1;
            else if (0 == strcmp(optarg, "off")) rgb[0] = 0; 
            else return -1; 
            break;
        case 'g':
            if(0 == strcmp(optarg, "on")) rgb[1] = 1;
            else if (0 == strcmp(optarg, "off")) rgb[1] = 0; 
            else return -1; 
            break;
        case 'b':
            if(0 == strcmp(optarg, "on")) rgb[2] = 1;
            else if (0 == strcmp(optarg, "off")) rgb[2] = 0; 
            else return -1; 
            break;
        case ':':
            print_usage();
            return -1;
            break;
        case '?':
            print_usage();
            return -1;
            break;
        default:
            print_usage();
            return -1;
            break;
        }
    }
    return 0;
}

int main(int argc, char* argv[])
{
    int fd, ret, val[3] = {0};
    if (7 != argc) {
        print_usage();
        return -1;
    }
    ret = parse_option(argc, argv, val);
    if (0 != ret) {
        print_usage();
        printf("parse option error\n");
        return -1;
    }

    fd = open(PATH, O_RDWR);
    if (fd < 0){
        printf("my_led open error\n");
        return -1;
    }
    ret = write(fd, &val, sizeof(val));
    if (ret < 0) {
        printf("write error\n");
        close(fd);
        return -1;
    }
    close(fd);
    return 0;
}
